package cn.gzjp.modules.woms.web.front.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.gzjp.common.constant.Constants;
import cn.gzjp.modules.woms.entity.Worker;
import cn.gzjp.modules.woms.service.WorkerService;
import cn.hutool.core.util.StrUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;

import me.chanjar.weixin.cp.bean.WxCpUser;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.gzjp.modules.wx.service.QyWxService;


/**
 * 企业号应用访问拦截器(前端拦截)
 */
public class WorkInterceptor implements HandlerInterceptor {

	public static Logger log = LoggerFactory.getLogger("womsLog");

	@Autowired
	private QyWxService qyWxService;
	@Autowired
	private WorkerService workerService;

	@Value("${corp.id}")
	private String corpId;

	@Value("${corp.debug}")
	private boolean corpDebug;


	
	
	/*
	 * 访问拦截，预处理访问请求
	 */
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HttpSession session = request.getSession();
		String userId = (String) request.getParameter("userId");
		if (StringUtils.isNoneBlank(userId)) {
			session.setAttribute("userId", userId);
		}
		userId = (String) session.getAttribute("userId");//openid

		session.setAttribute("corpId", corpId);//企业号id
		
		String agentId = (String)request.getParameter("agentId");//应用id
		if(StringUtils.isBlank(agentId)){
			agentId = (String) session.getAttribute("agentId");
		}
	    session.setAttribute("agentId", agentId);
		log.info("userId="+userId+"|corpId="+corpId+"|agentId="+agentId);
		Worker worker =  workerService.get(userId);
		//非测试模式，当前用户存在，头像为空
		if(!corpDebug&&worker!=null&& StrUtil.isBlank(worker.getHeadImg())){
			WxCpService wxCpService = this.qyWxService.getWxCpService(corpId, Constants.AgentId.worker);
			try {
				WxCpUser cpUser = wxCpService.userGet(userId);
				if(cpUser!=null){
					worker.setHeadImg(cpUser.getAvatar());
					workerService.save(worker);//更新用户头像
				}
			} catch (WxErrorException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
		}
	   if(StringUtils.isNotBlank(userId)){
			return true;
		}
		//已须通过微信Oauth认证，请求url中必须含以下2个参数
		synchronized (session.getId()) {
		String state = request.getParameter("state");
		String code = request.getParameter("code");
		if (StringUtils.isNotBlank(state)
				&& state.equals("qycms")
				&& StringUtils.isNotBlank(code)) {
			//认证信息中获取userId
			userId = this.handleFromOauth(corpId, agentId,code);
			session.setAttribute("userId", userId);
			return true;
		}else{
			//跳转到授权页面
				this.redirectOauth(request, response, corpId, agentId);
				return false;
			}
		}
	}
	
	
	/**
	 * 微信客户端请求时，须跳回微信Oauth认证，才能获取userid
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	private void redirectOauth(HttpServletRequest request,
			HttpServletResponse response, String corpId,String agentId) throws Exception {
		WxCpService wxCpService = this.qyWxService.getWxCpService(corpId, agentId);
		
		String redirectUri = request.getRequestURL().toString() + "?"
				+ request.getQueryString();
		
		String url = wxCpService.oauth2buildAuthorizationUrl(redirectUri,"qycms");
		

		System.out.println(url);
		response.sendRedirect(url);
		return;
	}

	/**
	 * 微信Oauth证后，再次访问商城时，认证信息中含userId
	 * @return 返回userId
	 * @throws WxErrorException
	 */
	private String handleFromOauth(String corpId,String agentId, String code) throws WxErrorException {
		String[] res = qyWxService.oauth2getUserInfo(corpId,agentId,code);
		return res[0];
		
	}

	

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}
	


}
